package blog.open1111.realm;

import blog.open1111.entity.Manager;
import blog.open1111.service.ManagerService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * Created by dengwubo on 2017/9/7.
 */
public class MyRealm extends AuthorizingRealm {

    @Autowired
    private ManagerService managerService;


    /**
     * 授权认证
     * @param principalCollection
     * @return
     */

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        return null;
    }


    /**
     * 验证当前登陆用户
     * @param authenticationToken
     * @return
     * @throws AuthenticationException
     */

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        String userName = (String)authenticationToken.getPrincipal();
        Manager manager = managerService.getByUserName(userName);
        if (manager!=null){
            SecurityUtils.getSubject().getSession().setAttribute("currentUser",manager);
            AuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(manager.getPassword(),manager.getPassword(),"xx");
            return authenticationInfo;
        }
        return null;
    }
}
